package com.cd.servlet;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cd.dao.MovieDao;
import com.cd.entity.Movie;
import com.cd.util.PageResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：处理电影相关的请求
 */
@WebServlet("/movie")
public class MovieServlet extends HttpServlet {
	private MovieDao movieDao;

	@Override
	public void init() throws ServletException {
		movieDao = new MovieDao();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		// 1. 获取请求参数cmd（区分前端的不同操作）
		String cmd = req.getParameter("cmd");
		// 2. 根据cmd的值，调用不同的方法处理不同的业务逻辑
		if (StrUtil.isNotBlank(cmd)) { // 相当于：cmd != null && cmd.trim().length() > 0
			if ("list".equals(cmd)) {   // 查询所有电影
				list(req, resp);
			}
			if ("findByPage".equals(cmd)) {  // 分页查询
				findByPage(req, resp);
			}
			if ("search".equals(cmd)) {      // 条件查询带分页
				search(req, resp);
			}
			if ("add".equals(cmd)) {        // 添加电影
				add(req, resp);
			}
			if ("update".equals(cmd)) {        // 修改电影
				update(req, resp);
			}
			if ("delete".equals(cmd)) {          // 删除电影
				delete(req, resp);
			}
			if ("findById".equals(cmd)) {        // 根据ID查询电影
				findById(req, resp);
			}
		}
	}

	// 删除电影
	private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取电影ID
		String movieIds = req.getParameter("movieIds");
		String[] split = movieIds.split(",");
		System.out.println("movieIds = " + movieIds);
		// 2. 删除电影
		movieDao.delete(split);
		// 3. 定义返回结果
		Map<String, String> map = new HashMap<>();
		map.put("code", "200");
		map.put("message", "删除电影成功！");
		// 4. 响应结果
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}

	// 添加电影
	private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();
		Movie movie = objectMapper.readValue(req.getInputStream(), Movie.class);
		// 2. 定义返回结果
		Map<String, String> map = new HashMap<>();
		try {
			// 3. 添加电影
			movieDao.add(movie);
			map.put("code", "200");
			map.put("message", "添加电影成功！");
		} catch (IOException e) {
			map.put("code", "500");
			map.put("message", "添加电影失败！");
		}
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}

	// 修改电影
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();
		Movie movie = objectMapper.readValue(req.getInputStream(), Movie.class);
		// 2. 定义返回结果
		Map<String, String> map = new HashMap<>();
		try {
			// 3. 修改电影
			movieDao.update(movie);
			map.put("code", "200");
			map.put("message", "修改电影成功！");
		} catch (IOException e) {
			map.put("code", "500");
			map.put("message", "修改电影失败！");
		}
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}

	// 条件查询带分页
	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取分页参数
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));
		// 2. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();
		Movie movie = objectMapper.readValue(req.getInputStream(), Movie.class);
		// 3. 开始分页带条件查询
		PageResult<Movie> pageResult = movieDao.search(page, pageSize, movie);
		String json = JSONUtil.toJsonStr(pageResult);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}

	// 分页查询
	private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取分页参数
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));
		PageResult<Movie> pageResult = movieDao.findByPage(page, pageSize);
		String json = JSONUtil.toJsonStr(pageResult);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}

	// 查询所有电影
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 查询所有电影
		List<Movie> movies = movieDao.findAll();
		// 2. 转换为json字符串并送到前端
		String json = JSONUtil.toJsonStr(movies);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}

	// 根据ID查询电影
	private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取电影ID
		String movieIdStr = req.getParameter("movieId");
		Long movieId = Long.parseLong(movieIdStr);
		// 2. 查询电影
		Movie movie = null;
		movieDao.findById(movieId);
		// 3. 定义返回结果
		Map<String, Object> map = new HashMap<>();
		if (movie != null) {
			map.put("code", "200");
			map.put("data", movie);
		} else {
			map.put("code", "404");
			map.put("message", "未找到该电影");
		}
		// 4. 响应结果
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}
}